<template>
  <van-skeleton title avatar :row="3" :loading="props.loading">
    <van-cell v-for="(user, i) in props.userList" :key="user.id">
      <van-card
        v-if="
          !isLogin ||
          props.isDetail === '1' ||
          (props.isDetail === '0' && currentUser.id != user.id)
        "
        :desc="user.profile"
        :title="`${user.username}(${user.planetCode})`"
        :thumb="user.avatarUrl"
        :tag="`${showTag && i == 0 ? '队长' : ''}`"
        @click="toUser(user)"
        @click-thumb.stop="showImagePreview([user.avatarUrl])"
      >
        <template #tags>
          <van-tag
            plain
            type="danger"
            v-for="tag in user.tags"
            style="margin-right: 0.5rem; margin-top: 0.5rem"
          >
            {{ tag }}
          </van-tag>
        </template>
        <template #footer>
          <van-button
            v-if="isLogin && !user.isMyFriend && currentUser.id != user.id"
            type="primary"
            size="small"
            @click.stop="showNotify(user.username, user.id)"
            >打招呼</van-button
          >
        </template>
      </van-card>
    </van-cell>
    <van-back-top right="15vw" bottom="10vh" />
    <van-empty v-if="isEmpty()" />
  </van-skeleton>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import { UserType } from "../models/user";
import { inject, onMounted, ref } from "vue";
import { getCurrentUser } from "../services/user";
import { showFailToast, showImagePreview } from "vant";
import myAxios from "../plugins/myAxios";

let socket: WebSocket | null = null;
const heartbeatInterval = 60 * 1000; // 60秒
let heartbeatTimer: string | number | NodeJS.Timer | null | undefined = null;
const startHeartbeat = () => {
  heartbeatTimer = setInterval(() => {
    if (socket.readyState === WebSocket.OPEN) {
      socket.send("PING");
    }
  }, heartbeatInterval);
};

//触发子组件事件以向父组件传值
const currentUser = ref({} as UserType); //当前用户
const emit = defineEmits(["showNotify"]);
const showNotify = async (username: string, toId: number) => {
  let sayHelloed = false;
  await myAxios
    .get("/chat/sayHello", {
      params: {
        toId,
        fromId: currentUser.value.id,
      },
    })
    .then((res) => {
      if (res.code === 0 && res.data) {
        showFailToast(`小智遗憾告知:不能重复向${username}打招呼`);
        sayHelloed = true;
      }
    });
  if (sayHelloed) return;
  const priMessage = {
    toId,
    fromId: currentUser.value.id,
    fromName: currentUser.value.username,
    fromUrl: currentUser.value.avatarUrl,
    text:
      "你好，我的昵称是" +
      currentUser.value.username +
      "，有些事情想与你交流一下，希望能得到你的回复！",
    createTime: new Date(),
    scope: 1,
    status: 0,
    type: 0,
  };
  socket.send(JSON.stringify(priMessage));
  emit("showNotify", true, username);
};

interface UserCardListProps {
  loading: boolean;
  userList: UserType[];
  showTag: boolean; //是否展示队长标签
  isGetUser: string; //未登录时是否跳转到登录页
  isDetail: string; //是否在列表展示自己的信息(只有在队伍详情页展示自己)
}
const props = withDefaults(defineProps<UserCardListProps>(), {
  loading: true,
  // @ts-ignore
  userList: [] as UserType[],
  showTag: false,
  isGetUser: "0",
  isDetail: "0",
});

//用户列表为空或者只有自己一人时展示空状态
const isEmpty = () => {
  if (!props.userList || props.userList.length < 1) return true;
  if (props.userList.length === 1 && props.isDetail === "0") {
    return props.userList[0].id === currentUser.value.id;
  }
  return false;
};

//访问别人主页
const reload = inject("reload"); //刷新页面的函数
const router = useRouter();
const toUser = (user) => {
  if (!currentUser.value) {
    showFailToast("小智遗憾告知:请先登录");
    return;
  }
  const userObj = JSON.stringify(user); //转为json方便传输
  router.push({
    path: "/user",
    query: {
      userObj,
    },
  });
  reload();
};

const isLogin = ref(false); //是否登录
onMounted(async () => {
  currentUser.value = await getCurrentUser(props.isGetUser);
  if (currentUser.value != null) {
    isLogin.value = true;
  }
  if (typeof WebSocket == "undefined") {
    showFailToast("小智遗憾告知:您的浏览器不支持WebSocket");
  } else {
    const isDev = process.env.NODE_ENV === "development";
    let socketUrl = isDev
      ? `ws://localhost:8081/api/websocket/${currentUser.value.id}/null`
      : `wss://gouhuo-backend.allbugs.top:8081/api/websocket/${currentUser.value.id}/null`;
    if (socket != null) {
      socket.close();
      socket = null;
    }
    socket = new WebSocket(socketUrl);
    //打开事件
    socket.onopen = function () {
      startHeartbeat();
      // console.log("websocket已打开");
    };
  }
});
</script>
